package multi_thread.train;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Cheng Jun
 * Description: 3个线程 交替打印 字母A 字母B 字母C
 * @version 1.0
 * @date 2022/6/9 16:33
 */
public class AlternatePrint1 {
    // 打印的次数
    private int times;
    // 所有线程共享的状态值
    private volatile int state;
    private Lock lock = new ReentrantLock();

    public AlternatePrint1(int times) {
        this.times = times;
    }

    public void printA() {
        print("A", 0);
    }

    public void printB() {
        print("B", 1);
    }

    public void printC() {
        print("C", 2);
    }

    public void print(String name, int stateNow) {
        for (int i = 0; i < times; ) {
            lock.lock();
            // 利用state 标识，表示哪个线程可以执行打印
            if (state % 3 == stateNow) {
                state++;
                i++;
                System.out.println(Thread.currentThread().getName() + " " + name);
            }
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AlternatePrint1 alternatePrint1 = new AlternatePrint1(2);
        new Thread(alternatePrint1::printC).start();
        Thread.sleep(10);
        new Thread(alternatePrint1::printA).start();
        new Thread(alternatePrint1::printB).start();
    }

}
